// import Vue from 'vue'
import {ElNotification, ElMessageBox} from 'element-plus'
/**
 * http错误处理
 */
export const errorDeal = (errorText) => {
    if (errorText == 'TOKEN过期') {
        ElMessageBox.alert('token过期，请重新登录！', '提示', {
            confirmButtonText: '确定',
            'show-close': false,
            callback: (action) => {
                window.location.href = '/'
            },
        })
    } else {
        ElNotification({
            title: '提示',
            type: 'warning',
            message: errorText,
            duration: 3000,
        })
    }
}
export const successDeal = (title) => {
    ElNotification({
        title: '成功',
        type: 'success',
        message: title,
        duration: 3000,
    })
}

/**
 * @describe 获取窗口宽高
 * @param
 * @return {Object}
 **/
export const getWindowWidthAndHeight = () => {
    return {
        windowHeight: document.documentElement.clientHeight || window.innerHeight || document.body.clientHeight,
        windowWidth: document.documentElement.clientWidth || window.innerWidth || document.body.clientWidth,
    }
}

/**
 * 存储localStorage
 */
export const setStore = (name, content) => {
    if (!name) return
    if (typeof content !== 'string') {
        content = JSON.stringify(content)
        // console.log(content);
    }
    window.localStorage.setItem(name, content)
}

/**
 * 获取localStorage
 */
export const getStore = (name) => {
    if (!name) return
    let content = window.localStorage.getItem(name)
    return isJsonString(content) ? JSON.parse(content) : content
}

/* 
 判断是否JsonString
 */
const isJsonString = (str) => {
    try {
        const toObj = JSON.parse(str) // json字符串转对象
        /*
          判断条件 1. 排除null可能性 
                   2. 确保数据是对象或数组
      */
        if (toObj && typeof toObj === 'object') {
            return true
        }
    } catch {}
    return false
}

/**
 * 删除localStorage
 */
export const removeStore = (name) => {
    if (!name) return
    window.localStorage.removeItem(name)
}
/**
 * 时间戳格式化
 */
export const getDateTime = function (timestamp) {
    let t = null
    // 不传值，则获取当前时间
    if (timestamp === undefined) {
        t = new Date()
    } else if (timestamp) {
        t = new Date(parseInt(timestamp))
    }

    if (t) {
        var n = t.getFullYear()
        var a = t.getMonth() + 1
        var r = t.getDate()
        var o = t.getHours()
        var i = t.getMinutes()
        var s = t.getSeconds()

        a >= 10 || (a = '0' + a), r >= 10 || (r = '0' + r), o >= 10 || (o = '0' + o), i >= 10 || (i = '0' + i), s >= 10 || (s = '0' + s)

        return [
            n, // yy 0
            a, // mm 1
            r, // dd 2
            n + '-' + a, // yy-mm 3
            a + '/' + r, // mm/dd 4
            o + ':' + i + ':' + s, // hh:mm:ss 5
            n + '-' + a + '-' + r + ' ' + o + ':' + i + ':' + s, // yy-mm-dd hh:mm::ss 6
            a + '-' + r + ' ' + o + ':' + i + ':' + s, // mm-dd hh:mm::ss 7
            n + '-' + a + '-' + r, // yy-mm-dd 8
            n + a + r, // yymmdd 9
            n + a, //yymm 10
        ]
    } else {
        return ['--', '--', '--', '--', '--', '--', '--', '--', '--']
    }
}
/**
 * 日期转时间戳
 */
export const getUnixTime = (e) => {
    var t
    if (e) {
        if (typeof e === 'string') e = e.replace(/-/g, '/').replace(/T|Z/g, ' ')
        t = new Date(e)
    } else t = new Date()
    return t.getTime()
}

/**
 * 日期转时间戳
 */
export const getTimestamp = (e) => {
    var t
    if (e) {
        e = e.replace(/-/g, '/')
        t = new Date(e)
    } else t = new Date()
    return t.getTime().toString()
}
/**
 * 日期加上‘-’
 */
export const getJoinDate = (e) => {
    e = e.toString()
    let year = e.substring(0, 4)
    let month = e.substring(4, 6)
    let day = e.substring(6, 8)
    let date = `${year}-${month}-${day}`
    return date
}
/**
 * 数组去重
 */
export const unique = (arr) => {
    return Array.from(new Set(arr))
}
/**
 * 获取地址栏参数
 */
export const getUrlParam = (e, url) => {
    var t = new RegExp('(^|&)' + e + '=([^&]*)(&|$)')

    var n = url ? url.match(t) : window.location.search.substr(1).match(t)
    console.log(url, '1')
    return n != null ? unescape(n[2]) : ''
}
/**
 * 哈希路由获取地址栏参数
 */

export const getUrlKey = (name) => {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ''])[1].replace(/\+/g, '%20')) || null
}

/**
 * 秒数格式化
 */
export const secondsFormat = (v = 0) => {
    v = parseInt(v)
    var day, minute, second, hour
    day = Math.floor(v / (60 * 60 * 24))
    hour = Math.floor((v % (60 * 60 * 24)) / (60 * 60))
    minute = Math.floor((v % (60 * 60)) / 60)
    second = Math.floor(v % 60)
    hour < 10 && (hour = '0' + hour)
    minute < 10 && (minute = '0' + minute)
    second < 10 && (second = '0' + second)
    return day != '00'
        ? day + '天' + hour + ':' + minute + ':' + second
        : hour != '00'
        ? hour + ':' + minute + ':' + second
        : minute != '00'
        ? minute + ':' + second
        : '00:' + second
}
/**
 * 手机格式化
 */
export const phoneFormat = (value, isNum) => {
    if (!value) return '--'
    if (isNum) {
        value = parseInt(value).toString()
    } else value = value.toString()

    let len = value.length
    let w = value.split('')
    w.splice(3, 0, '-')
    w.splice(8, 0, '-')
    w = w.join('')
    return w
}
/**
 * 去抖动函数
 */
export const debounce = function (wait, action) {
    let timeout
    return function () {
        let ctx = this
        let args = arguments

        if (timeout) clearTimeout(timeout)

        let callNow = !timeout
        timeout = setTimeout(() => {
            timeout = null
        }, wait)

        if (callNow) action.apply(ctx, args)
    }
}
/**
 * iframe 文件下载
 */
export const createDownload = (url, data, cb) => {
    var body = document.getElementsByTagName('body')[0]
    var ifr = document.getElementById('downLoadForm')
    var form = document.createElement('form')
    var input = document.createElement('input')
    if (!ifr) {
        ifr = document.createElement('iframe')
        ifr.setAttribute('id', 'downLoadForm')
        ifr.setAttribute('name', 'downLoadForm')
        ifr.setAttribute('style', 'display:none')
    }
    cb()
    ifr.addEventListener('load', function (e) {
        try {
            var res = ifr.contentWindow.document.body.textContent
            if (res != '' && res.indexOf('code') > -1) {
                var result = JSON.parse(res)
                if (res.code != 200) {
                    errorDeal(result)
                }
            }
        } catch (error) {
            errorDeal(error)
        }
    })

    form.setAttribute('style', 'display:none')
    form.setAttribute('target', 'downLoadForm')
    form.setAttribute('enctype', 'application/x-www-form-urlencoded;charset=utf-8')
    form.setAttribute('method', 'post')
    form.setAttribute('action', url)

    input.setAttribute('type', 'hidden')
    input.setAttribute('name', 'data')
    input.setAttribute('value', data)

    body.appendChild(ifr)
    body.appendChild(form)

    form.appendChild(input)
    form.submit()
    form.remove()
}

/* 文件流下载 */
export const BlobDownLoad = (res, name) => {
    let blob = new Blob([res.data], {type: 'application/vnd.ms-excel'})
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = name
    link.click()
    document.body.appendChild(link)
}
/* 文件地址下载 */
export const locationDownLoad = (url) => {
    if (!url) {
        errorDeal('无下载地址')
        return false
    }
    const link = document.createElement('a')
    link.href = url
    link.click()
    document.body.appendChild(link)
}
/**
 * 正则验证函数
 */
export const regularValid = function (type, value) {
    let valid = false

    switch (type) {
        case 'float': // 保留后两位校验
            valid = /^[-+]?[0-9]+\.?[0-9]{0,2}$/.test(value)
            break
        case 'int+': // 正整数
            valid = /^[1-9]+$/.test(value)
            break
        case 'phone': // 手机号码校验
            valid = /^1[3-9]\d{9}$/.test(value)
            break
        case 'name': // 账户名，数字+字母+下划线组合
            valid = !/\W+/.test(value)
            break
        case 'password': // 密码校验，非法字符
            valid = !/[`~()|{}':;',\[\].<>/?~！￥……&*（）——|{}【】‘；：”“'。，、？]/.test(value)
            break
        case 'email': // 邮箱
            valid = /^\w+@[a-z0-9]+\.[a-z]+$/.test(value)
            break
    }
    return valid
}

/**
 * 数字格式化
 */
export const numberFormat = function (num, pro = 100) {
    return num
        ? parseFloat((parseFloat(num) / pro).toFixed(2))
              .toString()
              .replace(/\d+/, function (n) {
                  return n.replace(/(\d)(?=(\d{3})+$)/g, function ($1) {
                      return $1 + ','
                  })
              })
        : 0.0
}

// 价格保留2位小数，每3位，分隔
export function thousands(num) {
    if (num) {
        return (parseFloat(num) / 100)
            .toFixed(2)
            .toString()
            .replace(/(\d)(?=(\d{3})+\.)/g, '$1,')
    } else {
        return '0.00'
    }
}

export const getNumberDateTime = function (value) {
    if (value) {
        var secondTime = parseInt(value) // 秒
        var minuteTime = 0 // 分
        var hourTime = 0 // 小时
        if (secondTime > 60) {
            //如果秒数大于60，将秒数转换成整数
            //获取分钟，除以60取整数，得到整数分钟
            minuteTime = parseInt(secondTime / 60)
            //获取秒数，秒数取佘，得到整数秒数
            secondTime = parseInt(secondTime % 60)
            //如果分钟大于60，将分钟转换成小时
            if (minuteTime > 60 || minuteTime == 60) {
                //获取小时，获取分钟除以60，得到整数小时
                hourTime = parseInt(minuteTime / 60)
                //获取小时后取佘的分，获取分钟除以60取佘的分
                minuteTime = parseInt(minuteTime % 60)
            }
        }
        var result = ''
        if (secondTime > 0) {
            result = '' + parseInt(secondTime) + '秒'
        }
        if (minuteTime > 0) {
            result = '' + parseInt(minuteTime) + '分' + result
        }
        if (hourTime > 0) {
            result = '' + parseInt(hourTime) + '小时' + result
        }
        return result
    }
}

export const bytesToSize = function (bytes) {
    if (bytes === 0) return '0 B'
    var k = 1000, // or 1024
        sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
        i = Math.floor(Math.log(bytes) / Math.log(k))

    return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i]
}

//初始化时间戳(毫秒)
export const initDatepicker = function (name, time = '') {
    if (!name) return
    let b = ''
    switch (name) {
        case 1: // 当前时间戳
            b = new Date().getTime()
            break
        case 2: // 当天的(23时23分59秒)
            b = new Date(new Date().toLocaleDateString()).getTime() - 999
            break
        case 3: // 当天的(00时00分00秒)
            b = new Date(new Date().toLocaleDateString()).getTime()
            break
        case 4: // 自定义时间 (当天的00时00分00秒 - 时间戳)
            b = new Date(new Date().toLocaleDateString()).getTime() - time
            break
    }
    return b
}

//重组路由数组  2级树
export const changeRouter = function (arr) {
    let otherMenu = [] //侧边栏影藏的菜单
    let asideMenu = [] //侧边栏的菜单

    arr.forEach((item) => {
        if (!item.hidden) {
            asideMenu.push({
                id: item.id,
                label: item.name,
                disabled: item.disabled,
                children: item.children && item.children.length && change(item.children),
            })
        } else {
            otherMenu.push(item.id)
        }
    })

    function change(arr) {
        let itemAsideMenu = []
        arr.forEach((item) => {
            if (!item.hidden) {
                itemAsideMenu.push({
                    id: item.id,
                    label: item.name,
                    disabled: item.disabled,
                })
            } else {
                otherMenu.push(item.id)
            }
        })
        return itemAsideMenu
    }

    return {
        otherMenu,
        asideMenu,
    }
}

// 根据角色id列表，过滤出需要的  菜单栏
export const filterMenu = function (routes, roleList) {
    let res = []
    routes.forEach((item) => {
        if (roleList.includes(item.id)) {
            res.push({
                ...item,
                children: item.children && item.children.length && change(item.children, roleList),
            })
        }
    })

    function change(list, roleList) {
        return list.filter((item) => roleList.includes(item.id))
    }
    // console.log(res,'菜单');
    return res
}
